package gui.panels.configurations;

import gui.actions.ImportAction;
import gui.actions.ResetAction;
import gui.models.ImportModel;
import gui.utils.ComponentUtils;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import common.Fictionator;

public class ImportPanel extends JPanel implements Observer {

	private static final long serialVersionUID = 1L;

	private JButton importButton;
	private JButton browseButton;
	private JButton cleanGuiSessionsButton;
	private JRadioButton manualImportButton;
	private JRadioButton autoImportButton;
	private JLabel actionLabel;
	private JTextField field;
	
	private final ImportModel model = new ImportModel();
	
    public ImportPanel() {
        model.addObserver(this);
    	buildPanel();
    }

    public void buildPanel() {
        setOpaque(false);
        
        String columnConstraints = "left:pref, 3dlu, pref:grow, pref, pref:grow, 3dlu, pref";
        String rowConstraints = "p, 3dlu, p, 3dlu, p, 7dlu, p, 7dlu, p:g, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, p:g";
                                                                         //10, 11,12,   13,14,   15
        
        FormLayout layout = new FormLayout(columnConstraints, rowConstraints);
        
//        JPanel form = new FormDebugPanel();
        JPanel form = new JPanel();
        
        PanelBuilder builder = new PanelBuilder(layout, form);
        builder.setDefaultDialogBorder();

        actionLabel = new JLabel();
        actionLabel.setVisible(false);
        
		field = new JTextField(35);
		field.setEditable(false);
		field.setBackground(Color.white);
		field.setBorder(BorderFactory.createLineBorder(Color.black));
		
		browseButton = ComponentUtils.createButton("Browse...");
		
		importButton = ComponentUtils.createButton("Start Import");
		importButton.setEnabled(false);
		
		manualImportButton = new JRadioButton("Choose a file:");
		manualImportButton.setOpaque(false);
		manualImportButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {		
			    if (!field.getText().isEmpty()) {
			        model.setSelectedFile(new File(field.getText()));
			    }
			    importButton.setEnabled(!field.getText().isEmpty());
                browseButton.setEnabled(true);
                field.setEnabled(true);
                model.setOnlineImport(false);
			}
		});
		manualImportButton.setSelected(true);
		
		autoImportButton = new JRadioButton("Online import.");	
		autoImportButton.setOpaque(false);
		autoImportButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {	
			    model.setSelectedFile(null);
				importButton.setEnabled(true);
				browseButton.setEnabled(false);
				field.setEnabled(false);
				model.setOnlineImport(true);
			}
		});
		
		ButtonGroup group = new ButtonGroup();
		group.add(manualImportButton);
		group.add(autoImportButton);
		
		browseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser fileOpener = new JFileChooser();
				FileFilter fileOpenerFilter = new FileNameExtensionFilter("fictional universe archive", "bz2");
				fileOpener.addChoosableFileFilter(fileOpenerFilter);
				
				int ret = fileOpener.showDialog(fileOpener, "Open");
				
				if (ret == JFileChooser.APPROVE_OPTION) {
					model.setSelectedFile(fileOpener.getSelectedFile());
					if (model.getSelectedFile() != null && model.getSelectedFile().isFile()) {
    					field.setText(" " + model.getSelectedFile().getPath());
    					importButton.setEnabled(true);
					} else {
					    importButton.setEnabled(false);
					    field.setText("");
					}
				}
			}
		});

		ImportAction importAction = new ImportAction(this, model);
		importButton.addActionListener(importAction);
		
		int guiSessionID = Fictionator.getInstance().getGuiSessionID();
		cleanGuiSessionsButton = ComponentUtils.createButton("Reset");
		cleanGuiSessionsButton.addActionListener(new ResetAction(this, guiSessionID));
		
		CellConstraints cc = new CellConstraints();
		builder.addSeparator("Import", cc.xyw(1, 1, 7)).setOpaque(false);
		builder.add(manualImportButton, cc.xy(1, 3));
		builder.add(field, cc.xyw(3, 3, 3, "fill, fill"));
		builder.add(browseButton, cc.xy(7, 3));
		builder.add(autoImportButton, cc.xy(1, 5));
		builder.add(importButton, cc.xy(4, 7));
		builder.add(actionLabel, cc.xyw(3, 9, 3, "center, fill"));
		builder.addSeparator("Reset Options", cc.xyw(1, 11, 7)).setOpaque(false);
		StringBuilder resetTextBuilder = new StringBuilder();
		resetTextBuilder.append("Use this button if trying to run an import operation results in a message saying there are currently other users ")
		    .append("connected. If there really are other users connected, you are strongly advised waiting for a better time. ")
		    .append("If however, the GUI was not closed in a clean way by a user, there may be leftovers in the table. ")
		    .append("This operation will clean those leftovers and allow you to perform an import. ")
		    .append("\nNote: If you happened to close to GUI while an import operation was in progress, it is strongly advised ")
		    .append("to run the import operation once again, otherwise the playing experience will not be very pleasent ");
		String resetText = ComponentUtils.addLineBreaks(resetTextBuilder.toString(), 90);
		JTextArea textArea = new JTextArea(resetText);
		textArea.setOpaque(false);
		builder.add(textArea, cc.xyw(1, 13, 7));
		builder.add(cleanGuiSessionsButton, cc.xy(1, 15));
		
        form.setOpaque(false);
        setLayout(new CardLayout());
        add("form", form);    
    }

    @Override
    public void update(Observable o, Object arg) {
        if (model.equals(o)) {
            boolean success = model.isSuccesfulImport();
            actionLabel.setText("Import " + (success ? "successful" : "failed") +  " at " + new Date());
            actionLabel.setVisible(true);
        }
    }
    
}
